﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using MUD.Lib.Commands;
using MUD.Lib.Utils;

namespace MUD.Lib.Objects.Users
{
    internal static class CommandHook
    {
        private static Collection<ICommand> Commands = new Collection<ICommand>();

        public static int NumOfCommands
        {
            get
            {
                return Commands.Count;
            }
        }

        static CommandHook() { }

        internal static void Initialize()
        {
            Assembly thisAssembly = Assembly.GetAssembly(Type.GetType("MUD.Lib.Master"));
            Type[] types = thisAssembly.GetTypes();
            foreach (Type type in types)
            {
                if (type.GetInterface("MUD.Lib.Commands.ICommand") != null)
                {
                    ICommand cmd = (ICommand)Activator.CreateInstance(type);
                    Commands.Add(cmd);
                }       
            }
        }

        internal static void ExecuteCommand(User user, string command)
        {
            string cmdName = command.Split(' ')[0].TrimNewline();
            foreach (ICommand cmd in Commands)
            {
                if (cmd.GetType().Name.Equals(cmdName)) 
                {
                    cmd.Execute(user, command);
                    return;
                }
            }
            user.Write(Strings.NoCommand);
        }
    }
}
